<template>
  <div class="box page-miH page-bgBack">
    <a-layout>
      <PageHeader @back="goBack" subTitle="返回">
        {{ "【" + detailList.name + "】" + detailList.personalPeriod
        }}{{ formType === "customer" ? "客户" : formType === "salary" ? "薪资" : formType === "social" ? "社保" : "" }}明细表
      </PageHeader>
      <div class="head">
        <div style="font-size: 18px; margin-left: 20px"></div>
      </div>

      <div class="fix-item-wrapper">
        <div class="fix-item-one">
          <p class="fix-item-name">合计</p>
        </div>
        <div class="fix-item-two">
          <div>
            <p class="childpProjectName">
              {{ formType === "customer" ? "本月人数" : formType === "salary" ? "本月计薪人数" : "本月参保人数" }}
            </p>
            <p class="childContentName">{{ detailList.empNumber ? detailList.empNumber : 0 }}人</p>
          </div>
          <div v-if="formType !== 'social'">
            <p class="childpProjectName">应发工资</p>
            <p class="childContentName">¥{{ detailList.shouldWages ? detailList.shouldWages : 0 }}</p>
          </div>
          <div v-if="formType !== 'social'">
            <p class="childpProjectName">实发工资</p>
            <p class="childContentName">¥{{ detailList.paidWages ? detailList.paidWages : 0 }}</p>
          </div>
          <div v-if="formType !== 'salary'">
            <p class="childpProjectName">企业社保</p>
            <p class="childContentName">¥{{ detailList.enterpriseSocialSecurity ? detailList.enterpriseSocialSecurity : 0 }}</p>
          </div>
          <div v-if="formType !== 'salary'">
            <p class="childpProjectName">企业公积金</p>
            <p class="childContentName">¥{{ detailList.enterpriseProvidentFund ? detailList.enterpriseProvidentFund : 0 }}</p>
          </div>
          <div>
            <p class="childpProjectName">服务费</p>
            <p class="childContentName">¥{{ detailList.serviceCharge ? detailList.serviceCharge : 0 }}</p>
          </div>
          <div v-if="formType !== 'salary'">
            <p class="childpProjectName">滞纳金</p>
            <p class="childContentName">¥{{ detailList.fine ? detailList.fine : 0 }}</p>
          </div>
          <div>
            <p class="childpProjectName">客户费用</p>
            <p class="childContentName">¥{{ detailList.customerFees ? detailList.customerFees : 0 }}</p>
          </div>
        </div>
      </div>
      <div class="operation">
        <div>
          <a-input-search allow-clear class="mr12" placeholder="姓名/手机号/身份证号" style="width: 180px" @search="inputChange" />
          <a-select style="width: 180px" @change="handleChange2" allowClear placeholder="员工状态">
            <!-- <a-select-option value="1">
            待入职
          </a-select-option> -->
            <a-select-option value="2"> 在职 </a-select-option>
            <a-select-option value="3"> 待离职 </a-select-option>
            <a-select-option value="4"> 离职 </a-select-option>
          </a-select>
        </div>
        <div>
          <a-button type="link" size="small" style="color: #767885; font-size: 12px" @click="reload">刷新<a-icon type="reload" /></a-button>
          <a-divider type="vertical" />
          <a-popover v-model="headVisible" title trigger="click" placement="bottom" @visibleChange="handleHeadChange">
            <div slot="content" style="width: 600px; height: 320px">
              <div>
                <div>已选择表头</div>
                <div class="overview-tag-wrapper">
                  <draggable v-model="tempSelectedHead" filter=".forbid" animation="3000" @start="onStart" @end="onEnd" :move="onMove">
                    <transition-group>
                      <a-tag
                        v-for="(item, index) in tempSelectedHead"
                        :key="index"
                        :closable="item.title !== '姓名' && item.title !== '身份证号'"
                        :color="item.title !== '姓名' && item.title !== '身份证号' ? '#fff' : '#E8E8E8'"
                        :class="
                          item.title !== '姓名' && item.title !== '身份证号' ? 'overview-select-tag' : 'overview-select-tag-name forbid'
                        "
                        @close="deleteSelectedHead($event, index)"
                        >{{ item.title }}</a-tag
                      >
                    </transition-group>
                  </draggable>
                </div>
              </div>
              <div>
                <div>可选择表头</div>
                <div>
                  <a-tag
                    v-for="(item, index) in tempNoSelectedHead"
                    :key="index"
                    class="overview-no-select-tag"
                    @click="addSelectedHead(index)"
                    >{{ item.title }}</a-tag
                  >
                </div>
              </div>
              <a-row type="flex" justify="end" style="position: absolute; bottom: 20px; right: 20px">
                <a-button style="margin-right: 12px" @click="handleHeadCancel">取消</a-button>
                <a-button type="primary" @click="handleHeadSearch">查询</a-button>
              </a-row>
            </div>
            <a-button type="link" size="small" style="color: #767885; font-size: 12px">选择表头<a-icon type="menu" /></a-button>
          </a-popover>
          <a-divider type="vertical" />
          <a-dropdown>
            <a-menu slot="overlay" @click="download">
              <a-menu-item key="8" :disabled="!dataList.length">全部导出</a-menu-item>
            </a-menu>
            <a-button type="link" size="small" style="color: #767885; font-size: 12px">导出<a-icon type="caret-down" /></a-button>
          </a-dropdown>
          <!-- <a-button style="margin-right:10px" @click="download" :disabled="!dataList.length">
            全部导出
          </a-button> -->
        </div>
      </div>
      <div class="tableBox">
        <a-table
          :loading="loading"
          :columns="columns"
          :data-source="dataList"
          :pagination="pagination"
          @change="handleTableChange"
          :scroll="{ x: 1200 }"
        >
          <template slot="shouldWages" slot-scope="text">
            {{ text ? text : 0 }}
          </template>
          <template slot="shouldWages" slot-scope="text">
            {{ text ? text : 0 }}
          </template>
          <template slot="empSocialSecurity" slot-scope="text">
            {{ text ? text : 0 }}
          </template>
          <template slot="enterpriseSocialSecurity" slot-scope="text">
            {{ text ? text : 0 }}
          </template>
          <template slot="empProvidentFund" slot-scope="text">
            {{ text ? text : 0 }}
          </template>
          <template slot="enterpriseProvidentFund" slot-scope="text">
            {{ text ? text : 0 }}
          </template>
          <template slot="tax" slot-scope="text">
            {{ text ? text : 0 }}
          </template>
          <template slot="paidWages" slot-scope="text">
            {{ text ? text : 0 }}
          </template>
          <template slot="serviceCharge" slot-scope="text">
            {{ text ? text : 0 }}
          </template>
        </a-table>
      </div>
    </a-layout>
  </div>
</template>
<script>
const initColumns = [
  {
    title: "姓名",
    dataIndex: "empName",
    key: "empName",
    width: 120,
    fixed: "left"
  },
  {
    title: "身份证",
    dataIndex: "idCard",
    key: "idCard",
    width: 230,
    fixed: "left"
  },
  {
    title: "应发工资",
    dataIndex: "shouldWages",
    key: "shouldWages",
    width: 120,
    scopedSlots: { customRender: "shouldWages" }
  },
  {
    title: "个人社保",
    dataIndex: "empSocialSecurity",
    key: "empSocialSecurity",
    width: 120,
    scopedSlots: { customRender: "empSocialSecurity" }
  },
  {
    title: "企业社保",
    dataIndex: "enterpriseSocialSecurity",
    key: "enterpriseSocialSecurity",
    width: 120,
    scopedSlots: { customRender: "enterpriseSocialSecurity" }
  },
  {
    title: "个人公积金",
    dataIndex: "empProvidentFund",
    key: "empProvidentFund",
    width: 140,
    scopedSlots: { customRender: "empProvidentFund" }
  },
  {
    title: "企业公积金",
    dataIndex: "enterpriseProvidentFund",
    key: "enterpriseProvidentFund",
    width: 140,
    scopedSlots: { customRender: "enterpriseProvidentFund" }
  },
  {
    title: "个人所得税",
    dataIndex: "tax",
    key: "tax",
    width: 140,
    scopedSlots: { customRender: "tax" }
  },
  {
    title: "实发工资",
    dataIndex: "paidWages",
    key: "paidWages",
    width: 120,
    scopedSlots: { customRender: "paidWages" }
  },
  {
    title: "服务费",
    dataIndex: "serviceCharge",
    key: "serviceCharge",
    width: 120,
    scopedSlots: { customRender: "serviceCharge" }
  }
];
import { getDetails, getTemplates, updateAutoTaxGrand, getSelectHeaders, updateHead } from "./api";
import draggable from "vuedraggable";
import axios from "axios";
import qs from "qs";
import ExportMixin from "xqjr-plugin-common/UploadOrExport/exportMixin";
const mixin = new ExportMixin();
export default {
  mixins: [mixin],
  components: { draggable },
  data() {
    return {
      tempSelectedHead: [],
      tempNoSelectedHead: [],
      headVisible: false,
      approStatus: false,
      abolitionVisible: false,
      tableName: undefined,
      generatelVisible: false,
      title: "",
      empVisible: false,
      empList: [],
      empIdsList: [],
      empIdList: [],
      createdList: [],
      salaryTemplateSalaryIdList: [],
      buttonArchive: {},
      isArchive: true,
      buttonState: true,
      inputName: null,
      companyName: this.$store.state.hr.companyName,
      isAll: false,
      selectedList: [],
      defaultSelectedKeys: [],
      chooseMemberVisible: false,
      selectedRowId: [],
      selectedRowKeys: [],
      loading: false,
      selectRowKey: [],
      dataList: [],
      initColumns,
      tableId: null,
      columns: [],
      detailList: [],
      allGroupId: [],
      groupList: [],
      empAllList: [],
      templateId: null,
      empStatus: null,
      salaryTemplateId: null,
      companyId: this.$store.state.hr.companyId,
      labelCol: { span: 4 },
      selectString: {},
      wrapperCol: { span: 14 },
      salaryGroupSalaryId: null,
      monthly: 5,
      yearly: 2021,
      bankType: undefined,
      statisticalVisible: false,
      formType: "",
      pagination: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: (total) => `共 ${total} 条`,
        showQuickJumper: true,
        showSizeChanger: true,
        personalPeriod: null,
        pageSizeOptions: ["10", "20", "50", "100"]
      }
    };
  },

  created() {
    this.detailList = JSON.parse(this.$route.query.dataList);
    console.log(this.detailList, this.formType, " this.detailList");
    this.monthly = this.$route.query.monthly;
    this.yearly = this.$route.query.yearly;
    this.formType = this.$route.query.formType;
    this.getDetailsList();
    this.getSelectHeaders();
    // this.initColumns.push({
    //   title: "服务费",
    //   dataIndex: "serviceCharge",
    //   key: "serviceCharge",
    //   width: 120
    // });
  },

  beforeDestory() {},
  methods: {
    reload() {
      this.getDetailsList();
      this.$notification["success"]({
        message: "成功",
        description: "刷新成功"
      });
    },
    getSelectHeaders() {
      getSelectHeaders({
        id: this.detailList.subjectId,
        type: this.detailList.type,
        customerDetailsIdList: this.detailList.customerDetailsIds,

        monthly: this.monthly,
        yearly: this.yearly
      }).then((res) => {
        var arr = [];
        this.selectString = res.data;
        this.tempSelectedHead = [];
        arr = JSON.parse(JSON.stringify(res.data.canSee));
        arr.forEach((item, index) => {
          if (item.fieldEnName) {
            this.tempSelectedHead.push({
              title: item.fieldName,
              dataIndex: item.fieldEnName,
              key: item.fieldEnName,
              width: item.fieldName === "身份证号" ? 200 : 130,
              fixed: item.fieldName === "姓名" || item.fieldName === "身份证号" ? "left" : null,
              fieldName: item.fieldName,
              fieldEnName: item.fieldEnName,
              isEdit: item.isEdit
            });
          } else {
            this.tempSelectedHead.push({
              title: item.fieldName,
              dataIndex: item.fieldName,
              key: item.fieldName,
              width: item.fieldName === "身份证号" ? 200 : 130,
              fixed: item.fieldName === "姓名" || item === "身份证号" ? "left" : null,
              fieldName: item.fieldName,
              fieldEnName: item.fieldEnName,
              isEdit: item.isEdit
            });
          }
        });
        this.columns = JSON.parse(JSON.stringify(this.tempSelectedHead));
        var arr2 = [];
        this.tempNoSelectedHead = [];
        // this.selectString = JSON.parse(JSON.stringify(this.selectString.split(",")));
        arr2 = JSON.parse(JSON.stringify(res.data.ignore));
        arr2.forEach((item, index) => {
          if (item.fieldEnName) {
            this.tempNoSelectedHead.push({
              title: item.fieldName,
              dataIndex: item.fieldEnName,
              key: item.fieldEnName,
              fieldName: item.fieldName,
              fieldEnName: item.fieldEnName,
              isEdit: item.isEdit
            });
          } else {
            this.tempNoSelectedHead.push({
              title: item.fieldName,
              dataIndex: item.fieldName,
              key: item.fieldName,
              fieldName: item.fieldName,
              fieldEnName: item.fieldEnName,
              isEdit: item.isEdit
            });
          }
        });
      });
    },
    handleHeadSearch() {
      this.selectString.canSee = this.tempSelectedHead;
      this.selectString.ignore = this.tempNoSelectedHead;
      updateHead(this.selectString).then((res) => {
        this.getSelectHeaders();
        this.headVisible = false;
      });
    },
    handleHeadChange(visible) {
      if (visible === false) {
        this.tempSelectedHead = JSON.parse(JSON.stringify(this.selectedHead));
        this.tempNoSelectedHead = JSON.parse(JSON.stringify(this.noSelectedHead));
      }
    },
    addSelectedHead(index) {
      const temp = JSON.parse(JSON.stringify(this.tempNoSelectedHead[index]));
      this.tempNoSelectedHead.splice(index, 1);
      this.tempSelectedHead.push(temp);
    },
    deleteSelectedHead(e, index) {
      e.preventDefault();
      const temp = JSON.parse(JSON.stringify(this.tempSelectedHead[index]));
      this.tempSelectedHead.splice(index, 1);
      this.tempNoSelectedHead.push(temp);
    },
    handleHeadCancel() {
      this.headVisible = false;
      this.tempSelectedHead = JSON.parse(JSON.stringify(this.selectedHead));
      this.tempNoSelectedHead = JSON.parse(JSON.stringify(this.noSelectedHead));
    },
    onStart() {
      this.drag = true;
    },
    onEnd() {
      this.drag = false;
    },

    onMove(e) {
      if (e.relatedContext.element.title === "姓名" || e.relatedContext.element.title === "身份证号") return false;
      return true;
    },
    autoAdd() {
      updateAutoTaxGrand({
        monthly: this.monthly,
        yearly: this.yearly,
        companyId: this.detailList.companyId,
        companyName: this.detailList.name,
        unpaidAmount: this.detailList.customerFees
      }).then((res) => {
        this.addVisible = false;
        this.$notification["success"]({
          message: "success",
          description: "生成成功"
        });
      });
    },
    onSelectChange(selectedRowKeys, selectedRow) {
      this.selectedRowId = [];
      this.selectedRowKeys = selectedRowKeys;
      if (this.selectedRowKeys.length) {
        this.buttonState = false;
      } else {
        this.buttonState = true;
      }
      selectedRow.forEach((item, index) => {
        this.selectedRowId.push(item.id);
      });
    },
    getTemplatesList() {
      this.columns = JSON.parse(JSON.stringify(this.initColumns));
      getTemplates({
        monthly: this.monthly,
        yearly: this.yearly,
        id: this.detailList.subjectId,
        type: this.detailList.type
      }).then((res) => {
        if (res.data.length > 0) {
          res.data.forEach((item, index) => {
            if (this.detailList.type === "group") {
              this.columns.splice(this.columns.length - 8, 0, {
                title: item.empName,
                dataIndex: item.empName,
                key: item.empName,
                width: 130
              });
            } else {
              this.columns.splice(this.columns.length - 7, 0, {
                title: item.empName,
                dataIndex: item.empName,
                key: item.empName,
                width: 130
              });
            }
          });
        }
      });
    },
    getDetailsList() {
      this.loading = true;
      getDetails({
        empStatus: this.empStatus,
        id: this.detailList.subjectId,
        type: this.detailList.type,
        customerDetailsIdList: this.detailList.customerDetailsIds,
        nameOrPhoneOrIdCard: this.inputName,
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize,
        monthly: this.monthly,
        yearly: this.yearly
      }).then((res) => {
        // this.getTemplatesList();
        this.loading = false;
        this.dataList = res.data.entities;
        this.pagination.total = res.data.entityCount; // 共多少条
        // this.pagination.pageSize = res.data.pageSize; // 每页多少条
        // this.pagination.current = res.data.pageNo; // 当前第几页
        if (res.data.entities && res.data.entities.length) {
          res.data.entities.forEach((item1, index1) => {
            let key = null;
            let value = null;
            if (item1.itemDetail !== null) {
              JSON.parse(item1.itemDetail).forEach((item2, index2) => {
                key = item2.name;
                value = item2.amount;
                this.dataList[index1][key] = value;
              });
            }
          });
        }
        console.log(this.dataList, "this.dataList???");
      });
    },
    handleChange2(e) {
      this.pagination.current = 1;
      this.pagination.pageSize = 10;
      this.empStatus = e;
      this.getDetailsList();
    },

    // 查询全部员工详情
    getEmpListAll() {
      // getEmpListAll({ companyId: this.companyId }).then(res => {
      //   this.empAllList = res.data;
      // });
    },
    getDownload() {
      axios({
        url: this.url,
        params: this.params,
        paramsSerializer: (param) => {
          return qs.stringify(param, { indices: false });
        },
        method: "get",
        responseType: "blob",
        headers: {
          token: this.token
        }
      })
        .then((res) => {
          if (res.data && res.data.type === "application/json") {
            const reader = new FileReader();
            reader.readAsText(res.data, "utf-8");
            reader.onload = () => {
              const resJson = JSON.parse(reader.result);
              this.$message.error(resJson.msg);
            };
          } else {
            const blob = new Blob([res.data], {
              type: "application/octet-stream"
            });
            const link = document.createElement("a");
            try {
              if (this.bankType === "HUAXIA_BANK") {
                link.download = this.excelName + ".txt";
              } else {
                link.download = this.excelName + ".xlsx";
              }
            } catch (err) {
              console.log("debug log --> ", res);
            }
            link.href = URL.createObjectURL(blob);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          }
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    bankChange(e) {
      this.bankType = e;
    },

    excelChange(e) {
      if (e && e.visibleWrong) {
        this.excelVisible = e.visibleWrong;
      } else {
        this.excelVisible = false;
        this.$router.push({
          path: "../add-payslip-sort",
          query: {
            tableId: this.tableId,
            month: this.monthly,
            year: this.yearly,
            sendName: this.tableName
          }
        });
      }
    },
    showStatistical() {
      this.statisticalVisible = true;
      this.bankType = undefined;
    },
    showGenerate() {
      this.generatelVisible = true;
      this.tableName = undefined;
    },
    // 录入截止上月个税累计

    // 返回
    goBack() {
      this.$router.go(-1);
      // this.$router.push({
      //   path: "/wages/monthly",
      //   query: {
      //     isBack: true,
      //     monthly: this.monthly,
      //     yearly: this.yearly
      //   }
      // });
    },

    // 导出
    download(i) {
      const token = this.$store.state.auth.token;

      this.exportData = {
        customerDetailsIdList: this.detailList.customerDetailsIds,
        nameOrPhoneOrIdCard: this.inputName,
        empStatus: this.empStatus,

        id: this.detailList.subjectId,
        type: this.detailList.type,
        monthly: this.monthly,
        yearly: this.yearly
      };
      this.url = `/hr/api/v1/childrenCompany/export`;
      this.excelName = `${this.detailList.name + this.detailList.personalPeriod}_` + "客户明细表导出详情" + ".xlsx";
      this.postDownload();
    },

    templateArchive() {
      this.abolitionVisible = true;
    },
    inputChange(e) {
      this.inputName = e;
      this.pagination.current = 1;
      this.pagination.pageSize = 10;
      this.getDetailsList();
    },

    // 分页
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.getDetailsList();
    }
  }
};
</script>
<style lang="scss" scoped>
$body-width: calc(100% - 338px);

.overview-no-select-tag {
  background-color: #fff;
  cursor: pointer;
  margin: 5px;
}
.overview-tag-wrapper {
  ::v-deep .ant-tag {
    .anticon-close {
      color: var(--primary);
    }
  }
}
.overview-tag-wrapper {
  ::v-deep .ant-tag {
    .anticon-close {
      color: var(--primary);
    }
  }
}
.overview-select-tag-name {
  cursor: pointer;
  margin: 5px;
  color: #666666;
}
.overview-select-tag {
  background-color: #fff !important;
  color: var(--primary) !important;
  border: 1px solid var(--primary);
  cursor: pointer;
  margin: 5px;
}
.head {
  padding: 0 20px 15px 20px;
  width: 100%;
  display: flex;
  text-align: center;
  line-height: 60px;
  justify-content: space-between;
  font-size: 20px;
  color: #000000;
  font-weight: 500;
  text-align: center;
  .anticon-left {
    color: #595959;
    font-size: 20px;
  }
}
.fix-item-wrapper {
  margin-left: 20px;
  margin-right: 20px;
  display: flex;
  height: 120px;
  background: #ffffff;
  border-radius: 8px;
  margin-bottom: 20px;
  padding: 33px;
  border: 1px solid #e8e8e8;
  display: flex;
  .fix-item-one {
    height: 40px;
    display: flex;
    align-self: center;
    padding-left: 40px;
    width: 15%;
    border-right: 1px solid #e8e8e8;
  }
  .fix-item-two {
    padding-left: 45px;
    margin-top: 10px;
    width: 85%;
    height: 45px;
    padding-right: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .fix-item-name {
    font-size: 18px;
    font-weight: 500;
    color: #222426;
    font-family: PingFangSC-Semibold, PingFang SC;
    line-height: 28px;
  }
}
.childpProjectName {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 300;
  color: #9c9c9c;
}
.childContentName {
  font-size: 18px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #333333;
}
.tableBox {
  margin-top: 20px;
  padding-left: 20px;
  padding-right: 20px;
}
.fix-item-wrapper {
  margin-left: 20px;
  margin-right: 20px;
  display: flex;
  // width: 100%;
  height: 120px;
  background: #ffffff;
  border-radius: 8px;
  margin-bottom: 20px;
  padding: 33px;
  border: 1px solid #e8e8e8;
  display: flex;
  .fix-item-one {
    height: 40px;
    display: flex;
    align-self: center;
    padding-left: 40px;
    width: 15%;
    border-right: 1px solid #e8e8e8;
  }
  .fix-item-two {
    padding-left: 45px;
    margin-top: 10px;
    width: 85%;
    height: 45px;
    padding-right: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .fix-item-name {
    font-size: 18px;
    font-weight: 500;
    color: #222426;
    font-family: PingFangSC-Semibold, PingFang SC;
    line-height: 28px;
  }
}
.childpProjectName {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 300;
  color: #9c9c9c;
}
.childContentName {
  font-size: 18px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #333333;
}
.operation {
  padding-left: 20px;
  padding-right: 20px;
  display: flex;
  justify-content: space-between;
}
.tableBox {
  margin-top: 20px;
  padding-left: 20px;
  padding-right: 20px;
}
</style>
